package xl.utils
{
	import flash.utils.Dictionary;
	
	import mx.utils.StringUtil;

	/**
	 * 多语言文本
	 * @author duguohui
	 *
	 */
	public class Language
	{
		private static var _table:Dictionary;

		/**
		 * 初始化语言包
		 * @param str
		 * @param initConstText
		 *
		 */
		public static function initLanguage(str:String, initConstText:Function = null):void
		{
			_table = new Dictionary();
			var lineArr:Array = str.split("\n");
			var lineCount:int = lineArr.length;

			for (var i:int = 0; i < lineCount; i++)
			{
				var lineText:String = lineArr[i];
				if (lineText.charCodeAt(lineText.length - 1) == 13)
					lineText = lineText.substr(0, lineText.length - 1);
				if (lineText == "" || lineText.substr(0, 2) == "//")
					continue;

				var separatorIndex:int = lineText.indexOf("=");
				var id:String = lineText.substr(0, separatorIndex);
				var text:String = lineText.substring(separatorIndex + 1);
				var intID:int = parseInt(id);
				var key:Object = (intID == 0 && id != "0") ? id : intID;
				_table.put(key, text);
			}

			if (initConstText != null)
				initConstText();
		}

		/**
		 * 返回语言文字字符串
		 * @param id
		 * @return
		 *
		 */
		public static function getString(key:Object, format:Array = null):String
		{
			if(!_table)
				return "";
			var text:String = _table.getValue(key);
			if(text==null)
			{
				return "";
			}
			text = StringUtils.replace(text, "\\n", "\n");
			if (format == null)
				return text;

			var len:int = format.length;
			if (len <= 0 || len % 2 == 1)
				return text;

			for (var i:int = 0; i < len; i += 2)
			{
				var pattern:RegExp = new RegExp("<" + format[i] + ">", "g");
				text = text.replace(pattern, format[i + 1]);
			}
			return text;
		}
	}
}
